<!-- 打包管理 - 预打包管理 新增查看编辑 -->
<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" prop="warehouseName">
              <el-select v-model="form.warehouseName" placeholder="请选择所属仓库" style="width:75%"  @change="warehouseClick($event)" :disabled="warehouseShow">
                <el-option
                  v-for="item in warehouseData"
                  :key="item.code"
                  :label="item.name"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" prop="shipmentName">
              <!-- <el-select v-model="form.shipmentName" placeholder="请选择所属入驻商  " style="width:75%" @change="shipmentClick" :disabled="isDetail">
                <el-option
                  v-for="item in shipmentList"
                  :key="item.partyCode"
                  :label="item.userName"
                  :value="item"
                />
              </el-select> -->
                <el-select v-model="shipmentValue" value-key="code" filterable placeholder="请选择所属入驻商" @change="shipmentClick" :disabled="isDetail" clearable style="width:75%">
                  <el-option
                    v-for="item in shipmentList"
                    :key="item.partyCode"
                    :label="item.userName"
                    :value="item"
                  />
                </el-select>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="包裹数" prop="packageQuantity">
              <el-input v-model="form.packageQuantity" style="width:75%" :disabled="isDetail" type="number" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注">
              <el-input v-model="form.remarks" style="width:88%" :disabled="isDetail" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      resizable
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      :key="tableRefresh"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      @edit-actived="editActivedEvent"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称"  width="270" v-if="this.operationType === 'detail' || !Boolean(form.shipmentCode)"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270" v-else>
        <template v-slot:edit="{ row }">
          <goodsSelect  :val2="form.shipmentCode" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位" width="270"></vxe-table-column>
      <vxe-table-column field="combinationQuantity" title="数量" width="270">
        <template v-slot="{ row }">
          <positive-number :value.sync="row.combinationQuantity" @input="inputQuantity(form.packageQuantity, $event, row)" @valErr="quantityReturn(row)" :disabled="isDetail" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="totalQuantity" title="总数量" width="120" >
      </vxe-table-column>
      <vxe-table-column field="availableStockQuantity" title="可用库存" width="150"></vxe-table-column>
      <vxe-table-column field="stockOutQuantity" title="缺货数量" width="120"></vxe-table-column>
      <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input', attrs: { disabled: nameDisabled }}" width="270"></vxe-table-column>
      <vxe-table-column title="操作"  fixed="right" min-width="100" v-if="operationType === 'add'">
        <template v-slot:default="{ row, rowIndex }">
          <vxe-button type="text" @click="insertEvent(rowIndex)">
            <i class="el-icon-plus"></i>
          </vxe-button>
          <vxe-button type="text" @click="delRowEvent(row,rowIndex)" v-if="row.isShow">
            <i class="el-icon-minus"></i>
          </vxe-button>
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作"  fixed="right" min-width="100" v-if="operationType === 'edit'">
        <template v-slot:default="{ row, rowIndex }">
          <vxe-button type="text" @click="insertEvent(rowIndex)">
            <i class="el-icon-plus"></i>
          </vxe-button>
          <vxe-button type="text" @click="delRowEvent(row,rowIndex)">
            <i class="el-icon-minus"></i>
          </vxe-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer"  v-if="operationType !== 'detail'">
      <el-button @click="saveClick"> 保 存 </el-button>
      <el-button @click="submitClick"> 提 交 </el-button>
      <!-- <el-button type="primary" @click="funcSubmitCheck" plain>返 回</el-button> -->
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'
  import '@/assets/iconfont/iconfont.css';
  import goodsSelect from '@/views/components/goodsSaleElSelect.vue'
  import { getWarehouse, getShipments } from '@/api/basicInfo'
  import PositiveNumber from '@/views/components/positiveNumber.vue'
  import { prepackagedAdd, prepackagedEdit, prepackagedDetail, queryUsefulInventory } from '@/api/packManagement/prePackaged'

  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  VXETable.use(VXETablePluginElement)
  export default {
    name: 'prePackagedAED',
    components: {
      goodsSelect,
      PositiveNumber
    },
    props:{
      operationType: {
        type: String,
        default: 'add'
      },
      operationCode: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        tableRefresh:1,
        isDetail: this.operationType === 'detail', // 详情的时候不可修改
        allAlign:'center',
        warehouseData:[],
        shipmentList: [],
        spanArr: [], // 一个空的数组，用于存放每一行记录的合并数
        pos: 0, // spanArr 的索引
        contentSpanArr: [],
        position: 0,
        form: {
          remarks: '',
          shipmentName:'',
          warehouseName: '',
        },
        loading: false,
        tableData: [{}],
        rules: {
          warehouseName: [
            { required: true, message: '请选择仓库', trigger: 'change' }
          ],
          shipmentName: [
            { required: true, message: '请选择入驻商', trigger: 'change' }
          ],
          packageQuantity: [
            { pattern: /^[0-9]*[1-9][0-9]*$/, message: '包裹数必须大于0的正整数' },
            { max: 11, message: '包裹数不能超过11位'}
          ]
        },
        validRules: {
          goodsName: [
            { required: true, message: '商品名称必须填写' },
          ],
          combinationQuantity: [
            { required: true, message: '数量必须填写' },
            { max: 20, message: '数量不能超过20位'}
          ],
        },
        listQuery: {
          page: 1,
          limit: 13,
          totalzong: 0
        },
        shipmentValue: '',
        nameDisabled: false,
        warehouseShow: true,
        fillInSum: ''
      }
    },
    watch: {
      'form.packageQuantity': {
        handler (val, oldVal) {
          // if(){}
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].combinationQuantity) {
              this.tableData[i].totalQuantity = this.tableData[i].combinationQuantity * val
              this.tableData[i].totalQuantity = parseFloat(this.tableData[i].totalQuantity.toFixed(6))
              if(this.tableData[i].availableStockQuantity - this.tableData[i].totalQuantity >= 0) {
                this.tableData[i].stockOutQuantity = 0
              }else {
                this.tableData[i].stockOutQuantity = this.tableData[i].totalQuantity - this.tableData[i].availableStockQuantity
                this.tableData[i].stockOutQuantity = parseFloat(this.tableData[i].stockOutQuantity.toFixed(6))
              }
            }
          }
          this.fillInSum = this.tableData.reduce((prev, cur) => prev + parseInt(cur.totalQuantity || 0), 0)
          let xTable = this.$refs.xTable
          xTable.updateFooter()
        },
        deep: true
      },
    },
    created() {
      // 仓库、入驻商查询
      this.getWarehouse()
      // 编辑和查看详情调用 详情数据接口
      if (this.operationType !== 'add') {
        this.getDetailData()
      }
      if (this.operationType === 'detail') delete this.rules
    },
    methods: {
      // 获取页面信息
      getDetailData(){
        prepackagedDetail(this.operationCode).then((res) => {
          this.form = res.data
          this.tableData = this.form.prepackagedItemWithDistributionVOList
          this.shipmentValue =  res.data.shipmentName
        })
      },
      // getInfo() {
      //   this.loading = true
      //   deliveryDetail(code).then(response => {
      //     this.form = response.data
      //     this.tableData = this.form.deliveryItemWithDistributionVOList
      //     this.form.receiverAddress = this.form.receiverProvince + ' ' + this.form.receiverCity + ' ' + this.form.receiverDistrict
      //     this.spanArr = [];
      //     this.contentSpanArr = [];
      //     for (var i = 0; i < this.tableData.length; i++) {
      //       if (i === 0) {
      //         this.spanArr.push(1);
      //         this.pos = 0;
      //         this.contentSpanArr.push(1);
      //         this.position = 0;
      //       } else {
      //         // 判断当前元素与上一个元素是否相同(第1和第2列)
      //         if (this.tableData[i].goodCode == this.tableData[i - 1].goodCode &&
      //           this.tableData[i].goodsName == this.tableData[i - 1].goodsName &&
      //           this.tableData[i].goodsBarCode == this.tableData[i - 1].goodsBarCode &&
      //           this.tableData[i].goodsUnitName == this.tableData[i - 1].goodsUnitName &&
      //           this.tableData[i].totalNum == this.tableData[i - 1].totalNum
      //         ) {
      //           this.spanArr[this.pos] += 1;
      //           this.spanArr.push(0);
      //         } else {
      //           this.spanArr.push(1);
      //           this.pos = i;
      //         }
      //       }
      //     }
      //     this.loading = false
      //   })
      // },
      //仓库、入驻商查询
      getWarehouse(){
        getWarehouse().then(response => {
          this.warehouseData = response.data
          if(this.warehouseData.length === 1) {
            this.warehouseShow = true
            this.form.warehouseCode = this.warehouseData[0].code
            this.form.warehouseName = this.warehouseData[0].name
          } else {
            this.warehouseShow = false
          }

        })
        getShipments().then(response => {
          this.shipmentList = response.data
        })
      },
      shipmentClick(e){
        this.shipmentValue = e
        this.form.shipmentName = e.userName
        this.form.shipmentCode = e.partyCode
        this.tableData = [{}]
        this.tableRefresh++
      },
      warehouseClick(e) {
        this.form.warehouseCode = e.code
        this.form.warehouseName = e.name
      },
      // 数量
      inputQuantity(packageQuantity = 1, combinationQuantity, row) {
        if(combinationQuantity === '.' || combinationQuantity === '..' || combinationQuantity === '...' || combinationQuantity === '....') {
          return
        }else {
          row.totalQuantity = combinationQuantity * packageQuantity
          row.totalQuantity = parseFloat(row.totalQuantity.toFixed(6))
          if (row.availableStockQuantity || row.availableStockQuantity === 0) {
            if(row.availableStockQuantity - row.totalQuantity >= 0) {
              row.stockOutQuantity = 0
            }else {
              row.stockOutQuantity = row.totalQuantity - row.availableStockQuantity
              row.stockOutQuantity = parseFloat(row.stockOutQuantity.toFixed(6))
            }
          }
          let xTable = this.$refs.xTable
          xTable.updateFooter()
        }
      },
      // 操作
      insertEvent(rowIndex) {
        const record = {
          isShow:'true'
        }
        this.tableData.splice(rowIndex + 1, 0, record)
      },
      delRowEvent(row, rowIndex) {
        this.$confirm('确认刪除吗？')
          .then(_ => {
            this.tableData.splice(rowIndex, 1)
          })
          .catch(_ => {})
      },
      // 保存
      saveClick() {
        this.form.prepackagedItemList = this.$refs.xTable.tableData
        let len = this.form.prepackagedItemList.length
        for(let i = 0; i < len; i++){
          if(!this.form.prepackagedItemList[i].goodsName)return this.$message.error('请选择商品')
          if(!this.form.prepackagedItemList[i].combinationQuantity)return this.$message.error('请输入数量')
        }
        if(!this.form.packageQuantity){
          this.form.packageQuantity = 1
        }
        const data = this.form
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细')
        } else {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              // const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
              // this.$refs.xTable.validate((valids) => {
              //   if(valids){
                  prepackagedAdd(data).then(response => {
                    this.$message({ message: response.msg, type: 'success' })
                    this.$emit('operationComplete')
                  }).then(() => {
                  })
              //   }else {
              //     return false
              //   }
              // })
            } else {
              return false
            }
          })
        }
      },
      // 提交submitClick
      submitClick(){
        this.form.prepackagedItemList = this.$refs.xTable.tableData
        let len = this.form.prepackagedItemList.length
        for(let i = 0; i < len; i++){
          if(!this.form.prepackagedItemList[i].goodsName)return this.$message.error('请选择商品')
          if(!this.form.prepackagedItemList[i].combinationQuantity)return this.$message.error('请输入数量')
        }
        if(!this.form.packageQuantity){
          this.form.packageQuantity = 1
        }
        const data = this.form
        if (!this.$refs.xTable.tableData.length) {
          this.$message.error('请新增明细')
        } else {
          this.$refs['form'].validate((valid) => {
            if (valid) {
              // const errMap = this.$refs.xTable.validate().catch(errMap => errMap)
              // this.$refs.xTable.validate((valids) => {
              //   if(valids){
                  prepackagedEdit(data).then(response => {
                    this.$message({ message: response.msg, type: 'success' })
                    this.$emit('operationComplete')
                  }).then(() => {
                  })
              //   }else {
              //     return false
              //   }
              // })
            } else {
              return false
            }
          })
        }
      },
      quantityReturn(row) {
        row.stockOutQuantity = ''
        row.totalQuantity = ''
        let xTable = this.$refs.xTable
        xTable.updateFooter()
      },
      //商品选择
      setGoodsCode(row){
        let obj = this.$refs.goodsSelect.obj
        row.goodsName = obj.name
        row.goodCode = obj.goodCode
        row.goodsCode = obj.code
        row.goodsUnit = obj.unitCode
        row.goodsUnitName = obj.basicUnitName
        row.goodsBarCode = obj.barCode
        row.packageQuantity = this.form.packageQuantity
        if(row.totalQuantity) {
          row.totalQuantity = row.totalQuantity
        } else {
          row.totalQuantity = 0
        }
        queryUsefulInventory(obj.code,this.form.warehouseCode,this.form.shipmentCode).then((res) => {
          row.availableStockQuantity = res.data.availableStockQuantity
          if(row.availableStockQuantity - row.totalQuantity >= 0) {
            row.stockOutQuantity = 0
          }else {
            row.stockOutQuantity = row.totalQuantity - row.availableStockQuantity
          }
        })
      },
      footerMethod ({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 1) {
              return '合计'
            }
            if (['totalQuantity','availableStockQuantity','stockOutQuantity'].includes(column.property)) {
              return parseFloat(XEUtils.sum(data, column.property).toFixed(6))
            }
            return '-'
          })
        ]
      },
      // 不许编辑
      editActivedEvent({ rowIndex, row }) {
        if (this.operationType === 'detail') {
          this.nameDisabled = rowIndex
          this.dateDisabled = !!row.date
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 50px auto;
    width: 200px;
    // float: right;
  }
  .el-select-dropdown__item.selected {
    color: #606266;
    font-weight: 400;
  }
</style>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar{padding:0 0 10px 0}
</style>
